package personal.leil.learning.digraph;

import personal.leil.learning.digraph.Edge;
import personal.leil.learning.digraph.Graph;
import personal.leil.learning.digraph.Node;

/**
 * 图构建器
 *
 * @author Leil
 * @version 1.0
 * @since 2024/1/22
 */
public class GraphBuilder {

    /**
     * 根据矩阵构建对应的图结构
     * <p>
     * <p>矩阵结构如下</p>
     * <pre>
     *         [[from1, to1, wight1],
     *          [from2, to2, wight2],
     *          [ ...              ]]
     *     </pre>
     * </p>
     *
     * @param matrix 矩阵
     * @return graph for building
     */
    public static Graph build(Integer[][] matrix) {
        Graph graph = new Graph();
        for (int i = 0; i < matrix.length; i++) {
            Integer from = matrix[i][0];
            Integer to = matrix[i][1];
            Integer weight = matrix[i][2];
            if (!graph.nodes.containsKey(from)) {
                graph.nodes.put(from, new Node(from));
            }
            if (!graph.nodes.containsKey(to)) {
                graph.nodes.put(to, new Node(to));
            }
            Node fromNode = graph.nodes.get(from);
            Node toNode = graph.nodes.get(to);

            Edge edge = new Edge(weight, fromNode, toNode);
            fromNode.out++;
            toNode.in++;
            fromNode.nextNodes.add(toNode);
            fromNode.edges.add(edge);
        }
        return graph;
    }

}
